package cn.helios.framework.scheduler.manager;

import lombok.extern.slf4j.Slf4j;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.stereotype.Service;

import java.text.ParseException;

/**
 * @author chenshiwen@ibabygroup.cn
 * @date 2017-10-20 13:46
 **/
@Slf4j
@Service
public class DefaultSchedulerJobService implements SchedulerJobService {

    @Override
    public void addJob(String name, String timer) {

        TaskJobDetail jobDetail = new TaskJobDetail();
        jobDetail.setTask(TaskManager.get());
        jobDetail.setJobClass(TaskJob.class);
        jobDetail.setKey(JobKey.jobKey(name, QuartzConstant.JOB_GROUP));

        CronTriggerImpl cronTrigger = new CronTriggerImpl();
        try {
            cronTrigger.setCronExpression(timer);
        } catch (ParseException e) {
            throw new RuntimeException("任务执行表达式错误", e);
        }
        TriggerKey triggerKey = TriggerKey.triggerKey(name, QuartzConstant.TRIGGER_GROUP);
        cronTrigger.setKey(triggerKey);

        try {
            SchedulerManager.addJob(jobDetail, cronTrigger);
        } catch (SchedulerException e) {
            throw new RuntimeException("任务添加失败", e);
        }
    }

    @Override
    public void modifyJob(String name, String timer) {
        CronTriggerImpl trigger;
        Scheduler scheduler = SchedulerManager.getScheduler();
        TriggerKey triggerKey = TriggerKey.triggerKey(name, QuartzConstant.TRIGGER_GROUP);
        try {
            trigger = (CronTriggerImpl) scheduler.getTrigger(triggerKey);
        } catch (SchedulerException e) {
            throw new RuntimeException("获取执行触发器异常", e);
        }

        if (trigger == null) {
            log.info("[{}]不存在调度器中", name);
            return;
        }

        // 时间不一致，执行修改
        if (!trigger.getCronExpression().equals(timer)) {
            try {
                trigger.setCronExpression(timer);
                // scheduler.resumeTrigger(triggerKey);  该方式不能生效
                scheduler.rescheduleJob(triggerKey, trigger);
            } catch (ParseException e) {
                throw new RuntimeException("任务执行表达式错误", e);
            } catch (SchedulerException e) {
                throw new RuntimeException("任务重启失败", e);
            }
        }
    }

    @Override
    public void deleteJob(String name) {
        try {
            SchedulerManager.getScheduler().deleteJob(JobKey.jobKey(name, QuartzConstant.JOB_GROUP));
        } catch (SchedulerException e) {
            throw new RuntimeException("删除任务失败", e);
        }
    }

}
